# -*- coding: utf-8 -*-
# Copyright 2017 Jarvis (www.odoomod.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import sys
from odoo import models, fields, api, _
from odoo.tools.misc import formatLang, format_date, get_user_companies
from odoo.exceptions import ValidationError
from ..lib import pycnamount
import json
import logging
_logger = logging.getLogger(__name__)


class MonthEndRule(models.Model):
    _name = 'month.end.rule'

    name = fields.Char('规则名称')
    month_end_account_account_ids = fields.Many2many(
        'account.account', string="用于结转科目", required=True,)

    month_end_account_account_dest_id = fields.Many2one(
        'account.account', string="结转最终科目", required=True,)


class AccountMoveLine(models.Model):
    _inherit = 'account.move.line'

    is_month_end = fields.Boolean(string="是否结转", defalut=False)


class AccountMove(models.Model):
    _inherit = 'account.move'

    is_month_end = fields.Boolean(string="是否结转", defalut=False)
    month_start_date = fields.Date(string="结转开始时间")
    month_end_date = fields.Date(string="结转结束时间")
    month_end_rule_id = fields.Many2one('month.end.rule', string="结转规则")
    month_end_info_widget = fields.Text()

    # @api.one
    # @api.depends('month_start_date','month_end_date')
    # def _get_month_end_info_JSON(self):
    #     self.payments_widget = json.dumps(False)
    # if self.payment_move_line_ids:
    #     info = {'title': _('Less Payment'), 'outstanding': False, 'content': self._get_payments_vals()}
    #     self.payments_widget = json.dumps(info, default=date_utils.json_default)

    def format_value(self, value, currency=False):
        currency_id = currency or self.env.user.company_id.currency_id
        if self.env.context.get('no_format'):
            return currency_id.round(value)
        if currency_id.is_zero(value):
            # don't print -0.0 in reports
            value = abs(value)
        res = formatLang(self.env, value, currency_obj=currency_id)
        return res

    def generate_aml(self, lines):
        if self.state == 'draft':
            if len(self.line_ids) > 0:
                self.sudo().write({'line_ids': [(5, 0, 0)]})
            tem_ids = []
            for line in lines:
                if(line['debit'] >= line['credit']):
                    line['debit'] = line['debit'] - line['credit']
                    if line['sum'] == False:
                        line['credit'] = line['debit']
                        line['debit'] = 0
                    else:
                        line['credit'] = 0
                else:
                    line['credit'] = line['credit'] - line['debit']
                    if line['sum'] == False:
                        line['debit'] = line['credit']
                        line['credit'] = 0
                    else:
                        line['debit'] = 0
                if(line['debit'] == 0 and line['credit'] == 0):
                    pass
                else:
                    tem_ids.append((0, 0, {
                        'account_id': line['account_id'],
                        'name': line['name'],
                        'debit': line['debit'],
                        'credit': line['credit'],
                        'is_month_end': True,
                    }))
            _logger.info(tem_ids)
            self.sudo().write({'line_ids': tem_ids})

    @api.one
    def button_month_end(self):
        data = {'lines': {'columns_header': [[
            {'name': ''
             },
            {'name': '日期', 'class': 'date'
             },
            {'name': '摘要'
             },
            {'name': '业务伙伴'
             },
            {'name': '借方', 'class': 'number'
             },
            {'name': '信用', 'class': 'number'
             },
            {'name': '余额', 'class': 'number'
             }
        ]],
            'lines': []
        }}
        generate_amls = []
        lines = []
        sum_debit = 0
        sum_credit = 0
        sum_balance = 0
        for account in self.month_end_rule_id.month_end_account_account_ids:
            amls = self.env['account.move.line'].sudo().search(
                [('account_id', '=', account.id), ('move_id.state', '=', 'posted'), ('is_month_end', '=', False),
                 ('date', '>=', self.month_start_date), ('date', '<=', self.month_end_date)])
            debit = 0
            credit = 0
            balance = 0
            for aml in amls:
                debit += aml.debit
                credit += aml.credit
                balance += aml.balance
            sum_debit += debit
            sum_credit += credit
            sum_balance += balance
            display_name = account.code + " " + account.name
            lines.append({
                'id': 'account_%s' % (account.id,),
                'name': account.display_name,
                'title_hover': display_name,
                'columns': [{'name': v} for v in [self.format_value(debit), self.format_value(credit), self.format_value(balance)]],
                'level': 2,
                'unfoldable': True,
                'unfolded': None,
                'colspan': 4,
            })
            generate_amls.append(
                {'account_id': account.id, 'name': self.month_end_rule_id.name, 'debit': debit, 'credit': credit, 'sum': False})
        lines.append({'id': 'general_ledger_total_1', 'name': '合计', 'class': 'total', 'level': 1, 'columns': [
            {'name': ''},
            {'name': ''},
            {'name': ''},
            {'name': self.format_value(sum_debit)},
            {'name': self.format_value(sum_credit)},
            {'name': self.format_value(sum_balance)}]
        })
        generate_amls.append({'account_id': self.month_end_rule_id.month_end_account_account_dest_id.id,
                              'name': self.month_end_rule_id.name, 'debit': sum_debit, 'credit': sum_credit, 'sum': True})
        data['lines']['lines'] = lines
        html = self.env['ir.ui.view'].render_template(
            "odoo12_account.main_month_end_table",
            values=dict(data),
        )
        self.generate_aml(generate_amls)
        self.month_end_info_widget = html

        # {'id': 'account_258', 'name': '1002.01 银行', 'title_hover': '1002.01 银行', 'columns': [
        #     {'name': '¥ 1,000.00'
        #      },
        #     {'name': '¥ 0.00'
        #      },
        #     {'name': '¥ 1,000.00'
        #      }
        # ], 'level': 2, 'unfoldable': True, 'unfolded': None, 'colspan': 4
        # },
        # {'id': 'account_210', 'name': '4001 实收资本', 'title_hover': '4001 实收资本', 'columns': [
        #     {'name': '¥ 0.00'
        #      },
        #     {'name': '¥ 1,000.00'
        #      },
        #     {'name': '¥ -1,000.00'
        #      }
        # ], 'level': 2, 'unfoldable': True, 'unfolded': None, 'colspan': 4
        # },
        # {'id': 'general_ledger_total_1', 'name': '合计', 'class': 'total', 'level': 1, 'columns': [
        #     {'name': ''
        #      },
        #     {'name': ''
        #      },
        #     {'name': ''
        #      },
        #     {'name': '¥ 1,000.00'
        #      },
        #     {'name': '¥ 1,000.00'
        #      },
        #     {'name': '¥ 0.00'
        #      }
        # ]
        # }
